package com.oracle.malldemo.servlet.items;

import com.alibaba.fastjson.JSON;
import com.oracle.malldemo.domain.Items;
import com.oracle.malldemo.view.JsonData;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(value="/items/details")
public class QueryItemById extends ItemsServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/plain;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        Items item = null;
        try {
            String id = req.getParameter("id");
            item = itemsService.queryItemById(Integer.parseInt(id));
            JsonData result = JsonData.success("查询商品资料成功！", item);
            out.write(JSON.toJSONString(result));
            out.flush();
            out.close();
        } catch (Exception ex) {
            ex.printStackTrace();
            JsonData result = JsonData.fail("程序出现异常！", null);
            out.write(JSON.toJSONString(result));
            out.flush();
            out.close();
        }
    }
}
